<template>
  <view class="signature-page">
    <canvas id="signature-canvas" @touchstart="startDraw" @touchmove="draw" @touchend="endDraw"></canvas>
    <button @click="rotateImage">旋转</button>
    <button @click="positionImage">调整位置</button>
    <button @click="exportImage">导出</button>
    <image :src="signatureImage"></image>
  </view>
</template>

<script>
import { getOrientation, rotateImage } from '@/utils/imageHelper'

export default {
  data() {
    return {
      signatureImage: '', // 存储合成后的签名图片
      startX: 0,
      startY: 0,
      ctx: null,
      isDrawing: false,
    }
  },
  methods: {
    startDraw(event) {
      this.startX = event.touches[0].clientX - event.target.offsetLeft
      this.startY = event.touches[0].clientY - event.target.offsetTop
      this.isDrawing = true
    },
    draw(event) {
      if (!this.isDrawing) return
      const x = event.touches[0].clientX - event.target.offsetLeft
      const y = event.touches[0].clientY - event.target.offsetTop
      this.ctx.beginPath()
      this.ctx.moveTo(this.startX, this.startY)
      this.ctx.lineTo(x, y)
      this.startX = x
      this.startY = y
      this.ctx.stroke()
    },
    endDraw() {
      this.isDrawing = false
    },
    async rotateImage() {
      // 获取当前设备方向
      const orientation = await getOrientation()

      // 实现图片旋转逻辑
      const signatureCanvas = uni.createSelectorQuery().select('#signature-canvas')
      signatureCanvas.fields({ node: true, size: true }).exec(async (res) => {
        const canvasNode = res[0].node
        const canvasSize = res[0].width > res[0].height ? res[0].width : res[0].height
        const ctx = canvasNode.getContext('2d')
        ctx.clearRect(0, 0, canvasSize, canvasSize) // 清空 canvas
        ctx.translate(canvasSize / 2, canvasSize / 2) // 将坐标原点移至画布中心
        if (orientation === 'portrait') {
          ctx.rotate((90 * Math.PI) / 180) // 旋转 90 度
        }
        // 绘制签名内容
        ctx.draw(true, async () => {
          const tempFilePath = await uniCanvasToTempFilePath(canvasNode)
          const rotatedFilePath = await rotateImage(tempFilePath)
          this.signatureImage = rotatedFilePath
        })
      })
    },
    positionImage() {
      // 实现图片位置调整逻辑
    },
    exportImage() {
      // 将签名图片合成到合同图片中并导出
    },
  },
  mounted() {
    // 获取 canvas 上下文
    const ctx = uni.createCanvasContext('signature-canvas', this)

    // 设置 canvas 大小
    ctx.canvas.width = 300
    ctx.canvas.height = 150

    // 保存上下文对象
    this.ctx = ctx
  },
}
</script>
<style lang="scss" scoped>
.signature-page {
  display: flex;
  flex-direction: column;
  align-items: center;
}

#signature-canvas {
  border: 1px solid #ccc;
  margin: 10px;
}
</style>